logo头像
Snippet 博客主题

android Flutter 7.数据存储-shared_preferences

本文于375天之前发表,文中内容可能已经过时。

android Flutter 7.数据存储-shared_preferences

通常我们必须编写本地平台集成以在两个平台上存储数据。
幸运的是,shared_preferences 插件可用于在磁盘上保存键值数据。
共享首选项插件包装NSUserDefaults在iOS和SharedPreferencesAndroid上,为简单数据提供持久存储。

  • 1.添加依赖项
  • 2.保存数据
  • 3.读取数据
  • 4.删除数据

1.添加依赖项

在我们开始之前,我们需要将shared_preferences 插件添加到我们的pubspec.yaml文件中:

1
2
3
4
dependencies:
flutter:
sdk: flutter
shared_preferences: "<newest version>"

2.保存数据

为了保存数据,我们可以使用SharedPreferences该类提供的setter方法 。设置器方法可用于各种原始类型,例如setInt,setBool,和setString。

Setter方法做两件事:首先,同步更新内存中的键值对。然后,将数据保存到磁盘。

1
2
3
4
5
// obtain shared preferences 
final prefs = await SharedPreferences.getInstance();

// set new value
prefs.setInt('counter', counter);

3.读取数据

要读取数据,我们可以使用SharedPreferences该类提供的适当的getter方法 。对于每个制定者都有一个相应的获得者。例如,我们可以使用getInt,getBool和getString方法。

1
2
3
4
final prefs = await SharedPreferences.getInstance();

// Try reading data from the counter key. If it does not exist, return 0.
final counter = prefs.getInt('counter') ?? 0;

4.删除数据

要删除数据,我们可以使用该remove方法。

1
2
3
final prefs = await SharedPreferences.getInstance();

prefs.remove('counter');

支持的类型

虽然使用键值存储非常简单方便,但它有一些限制:

只有基本类型可以使用:int,double,bool,string和stringList
它不是用来存储大量数据的。

测试支持

测试持续使用数据的代码可能是一个好主意 shared_preferences。为此,我们需要嘲笑图书馆MethodChannel使用的shared_preferences。

SharedPreferences通过setupAll在我们的测试文件中的一个方法中运行以下代码,我们可以在我们的测试中填充初始值:

1
2
3
4
5
6
7
const MethodChannel('plugins.flutter.io/shared_preferences')
.setMockMethodCallHandler((MethodCall methodCall) async {
if (methodCall.method == 'getAll') {
return <String, dynamic>{}; // set initial values here if desired
}
return null;
});

例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
// This widget is the root of our application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Shared preferences demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Shared preferences demo'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;

@override
_MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;

@override
void initState() {
super.initState();
_loadCounter();
}

//Loading counter value on start
_loadCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_counter = (prefs.getInt('counter') ?? 0);
});
}

//Incrementing counter after click
_incrementCounter() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
_counter = (prefs.getInt('counter') ?? 0) + 1;
setState(() {
_counter;
});
prefs.setInt('counter', _counter);
}

@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'You have pushed the button this many times:',
),
new Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: new Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}

支付宝打赏 微信打赏

打赏